/*
 * texture.cpp
 *
 *  Created on: 10-nov-2012
 *      Author: dna
 */

#include "texture.h"

bool ImageLoad(char *filename, Image *image) {
	FILE *file;
	unsigned long size;                 // size of the image in bytes.
	unsigned long i;                    // standard counter.
	unsigned short int planes;          // number of planes in image (must be 1)
	unsigned short int bpp;             // number of bits per pixel (must be 24)
	char temp;                          // temporary color storage for bgr-rgb conversion.

	// make sure the file is there.
	if ((file = fopen(filename, "rb"))==NULL){
		cout << "File Not Found : " << filename << endl;
		return false;
	}

	// seek through the bmp header, up to the width/height:
	fseek(file, 18, SEEK_CUR);

	// read the width
	if ((i = fread(&image->sizeX, 4, 1, file)) != 1) {
		cout << "Error reading width from " << filename << endl;
		return false;
	}
	printf("Width of %s: %lu\n", filename, image->sizeX);

	// read the height
	if ((i = fread(&image->sizeY, 4, 1, file)) != 1) {
		cout << "Error reading height from %s " << filename << endl;
		return false;
	}
	cout << "Height of " << filename << ": " << image->sizeY << endl;

	// calculate the size (assuming 24 bits or 3 bytes per pixel).
	size = image->sizeX * image->sizeY * 3;

	// read the planes
	if ((fread(&planes, 2, 1, file)) != 1) {
		cout << "Error reading planes from " << filename << endl;
		return false;
	}
	if (planes != 1) {
		cout << "Planes from " << filename << " is not 1: " << planes << endl;
		return false;
	}

	// read the bpp
	if ((i = fread(&bpp, 2, 1, file)) != 1) {
		cout << "Error reading bpp from " << filename << endl;
		return false;
	}
	if (bpp != 24) {
		cout << "Bpp from " << filename << " is not 24: " << bpp << endl;
		return false;
	}

	// seek past the rest of the bitmap header.
	fseek(file, 24, SEEK_CUR);

	// read the data.
	image->data = (char *) malloc(size);
	if (image->data == NULL) {
		cout << "Error allocating memory for color-corrected image data" << endl ;
		return false;
	}

	if ((i = fread(image->data, size, 1, file)) != 1) {
		cout << "Error reading image data from " << filename << endl;
		return false;
	}

	for (i=0;i<size;i+=3) { // reverse all of the colors. (bgr -> rgb)
		temp = image->data[i];
		image->data[i] = image->data[i+2];
		image->data[i+2] = temp;
	}

	fclose(file);

	return true;
}
